var express = require('express');
var path = require('path');
var fs = require('fs');
var querydb = require('../utils/querydb');
var upload = require('../utils/fileupload_util');
var jwt = require('jsonwebtoken');
var router = express.Router(); //获取路由对象

// =======it.warmtel.com => 重定向到 => 雨果笔记======
router.get('/', (req, res) => {
    res.redirect('http://www.yuguoxy.com/geekhome');
});


//=========================================
//============= 操作员模块 ===================
//=========================================

//根据用户名密码查询用户接口:/api/login
router.post("/api/login", function (req, res) {
    var username = req.body.username; //接收表单参数
    var password = req.body.password;
    console.log(`username ${username}  password= ${password}`);
    var sql = "SELECT m_id,username,password,headerimg,createtime,nick FROM y_manager WHERE username = ? and password = ?";
    var parameters = [username, password];
    querydb(sql, parameters).then(function (data) {
        if (data != null && data.length > 0) {
            const userToken = {
                name: username,
                originExp: Date.now() + 60 * 60 * 1000, // 设置过期时间（毫秒）为 1 小时
            }
            const secret = 'vue-web-secret'; // 指定密钥，这是之后用来判断 token 合法性的标志
            const token = jwt.sign(userToken, secret); // 签发 token
            req.session.token = token; // 保存token到session， 用于后续请求接口token鉴权
            console.log(' req.session.token111 >>> ', req.session.token);
            res.send({
                resultCode: 1,
                resultInfo: data[0],
                token: token,
            })
        } else {
            res.send({
                resultCode: -1,
                resultInfo: '用户名密码出错!',
            });
        }
    });
})


/**
 * 注册-操作员添加
 * /api/register
 */
router.post("/api/register", upload.single('headerimg'), function (req, res) {
    const username = req.body.username; //接收表单用户名参数
    const password = req.body.password; //密码
    const nick = req.body.nick; //nick
    const createtime = req.body.createtime; //时间

    console.log('register >>>>>> ',username,password,nick,createtime);

    const sql = "INSERT INTO y_manager (username,password,nick,createtime,headerimg) VALUES (?,?,?,?,?)";
    const parameters = [username, password, nick, createtime, req.session.headerimg];

    querydb(sql, parameters).then(function (data) {
        console.log("插入数据成功!");
        res.send({
            resultCode: 1,
            resultInfo: 'ok',
        });
    }).catch(error => {
        console.log(error);
        res.send({
            resultCode: -1,
            resultInfo: 'no' + error,
        });
    });

});

//退出接口
router.get("/api/logout", function (req, res, next) {
    // 清除session
    res.send({
        resultCode: 1,
        resultInfo: 'ok',
    });
});


/**
 * 操作员列表
 */
router.get("/api/manager/list", function (req, res) {
    var sql = "SELECT * FROM y_manager";
    querydb(sql).then(function (data) {
        console.log(JSON.stringify(data));
        if (data != null && data.length > 0) {
            res.send({
                resultCode: 1,
                resultInfo: data,
            })
        } else {
            res.send({
                resultCode: -1,
                resultInfo: '没有数据',
            });
        }
    })
});

/**
 * 动态菜单
 */
router.get("/api/sysmenu", (req, res, next) => {
    fs.readFile('./data/sysmenu.json', (err, result) => {
        if (err) {
            console.log('读文件出错' + err);
            return;
        }
        let menuData = JSON.parse(result.toString());
        res.send({
            code: 200,
            sysmenu: menuData
        })
    })
})

/**
 * 查检用户是否存在
 */
//根据id查询用户接口:/api/find
router.get("/api/manager/find", function (req, res, next) {
    var username = req.query.username; //接收表单参数

    var sql = "SELECT * FROM y_manager WHERE username = ?";
    var parameters = [username];

    querydb(sql, parameters).then(function (data) {
        if (data != null && data.length > 0) {
            
            res.send({
                resultCode: 1,
                resultInfo: data,
            })
        } else {
            res.send({
                resultCode: -1,
                resultInfo: '没有数据',
            });
        }
    });

});

//=========================================
//============= 访客模块 ===================
//=========================================

//添加用户接口 post请求:/api/add
router.post("/api/add", upload.single('fileHeader'), function (req, res) {
    const userName = req.body.username; //接收表单用户名参数
    const age = req.body.age; //年龄
    const sex = req.body.sex; //性别 0 男 1 女
    const visitGoal = req.body.visitgoal; // 到访问目的
    const visittime = req.body.visittime; // 到访问时间
    const education = req.body.education; // 学历
    const company = req.body.company; //公司，单位

    // console.log(`name ${userName}, age: ${age}, sex :${sex}, visitGoal : ${visitGoal}, visittime : ${visittime}, education : ${education}, company : ${company}`);

    const sql = "INSERT INTO y_user (username,headerimg,age,sex,visitgoal,visittime,education,company) VALUES (?,?,?,?,?,?,?,?)";
    const parameters = [userName, req.session.headerimg, age, sex, visitGoal, visittime, education, company];

    querydb(sql, parameters).then(function (data) {
        console.log("插入数据成功!");
        res.send({
            resultCode: 1,
            resultInfo: 'ok',
        });
    }).catch(error => {
        console.log(error);
        res.send({
            resultCode: -1,
            resultInfo: 'no' + error,
        });
    });

});

router.get('/api/list', (req, res) => {
    var pageSize = 12; // 每页记录条数
    var totalNo = 0; // 总记录条数
    var pagesNum = 0; // 总页数
    if (req.query.pageSize) {
        pageSize = req.query.pageSize;
        pageSize = parseInt(pageSize);
    }
    // ===接收参数页号====
    var currentNo = req.query.pageNo; // 当前页号

    console.log('currentNo :' + currentNo, ' pageSize :', pageSize);
    
    if (currentNo == null && typeof (currentNo) === 'undefined') {
        currentNo = 1;
    }

    // ==== 总页数

    querydb('SELECT count(*) as num FROM y_product').then(data => {
        totalNo = data[0].num; // 总记录条数
        if (totalNo % pageSize === 0) {
            pagesNum = totalNo / pageSize;
        } else {
            pagesNum = totalNo / pageSize + 1;
        }
        // console.log('总页数 ' + parseInt(pagesNum));

        // ==== 根据偏移量查询分页记录
        var start = (currentNo - 1) * pageSize; // 偏移量

        var sql = "SELECT y_product.id,shop,picture,product,price,oldprice,putaway,detail, y_category.name as categoryname FROM y_product,y_category WHERE y_product.category_id = y_category.id ORDER BY id DESC  LIMIT ?, ? ";
        var param = [start, pageSize];
        return querydb(sql, param);
    }).then(dataTwo => {
        // console.log(JSON.stringify(dataTwo));
        if (dataTwo != null && dataTwo.length > 0) {
            res.send({
                resultCode: 1,
                resultInfo: {
                    total: totalNo,
                    currentNo: parseInt(currentNo),
                    pageSize: parseInt(pageSize),
                    totalNum: parseInt(pagesNum),
                    list: dataTwo
                },
            })
        } else {
            res.send({
                resultCode: -1,
                resultInfo: '没有数据',
            });
        }
    })
})


//根据id查询商品接口:/api/find
router.get("/api/find", function (req, res, next) {
    var id = req.query.id; //接收表单参数
    if (!id) {
        res.send({
            resultCode: -1,
            resultInfo: '参数出错',
        })
        return
    }
    var sql = "SELECT id,shop,picture,product,price,oldprice,putaway,detail,category_id FROM y_product WHERE id = ?";
    var parameters = [id];

    querydb(sql, parameters).then(function (data) {
        // res.send(JSON.stringify(data[0]));
        res.send({
            resultCode: 1,
            resultInfo: data[0],
        });
    }).catch(next);

});

//删除商品接口:/api/delete
router.get("/api/delete", function (req, res) {
    var id = req.query.uid;
    querydb('SELECT headerimg FROM y_user WHERE uid =?', id).then(data => {
        console.log(data);
        if (data.length == 0) {
            res.send({
                resultCode: 1,
                resultInfo: 'ok',
            })
            return
        }

        // 删除图片文件
        let headerImg = data[0].headerimg;
        if (headerImg && headerImg !== '') {
            var headerDir = path.join(path.resolve('.'), 'public/', headerImg);
            //fs.unlink删除文件  
            fs.unlink(headerDir, function (error) {
                if (error) {
                    console.log(error);
                    return false;
                }
                console.log('删除文件成功');
            });
        }
        // 删除数据库记录
        querydb("DELETE FROM y_user WHERE uid = ?", id).then(function (data) {
            console.log("删除成功!  :" + JSON.stringify(data));
            res.send({
                resultCode: 1,
                resultInfo: 'ok',
            })
        })

    })
})

/**
 * 批量删除
 * ids:[1,2,3]
 */
router.post("/api/deletebatch", function (req, res) {
    var ids = req.body.ids;
    var sql = "DELETE FROM y_user WHERE uid IN (" + ids + ")"
    querydb(sql).then(function (data) {
        console.log("删除成功!  :" + JSON.stringify(data));

        res.send({
            resultCode: 1,
            resultInfo: 'ok',
        });
    });

});

/**
 * 单文件上传接口
 * /api/uploadFile 
 * headerImg
 */
router.post("/api/uploadFile", upload.single('headerImg'), function (req, res) {
    // console.log('图片上传>>' + req.session.headerimg+ " username ="+userName+"  password = "+passWord);
    res.send(`${req.session.headerimg}`);
});

//修改用户接口 post请求:/api/update
router.post("/api/update", function (req, res) {
    var id = req.body.id;
    var userName = req.body.username; //接收表单用户名参数
    const age = req.body.age; //年龄
    const sex = req.body.sex; //性别 0 男 1 女
    const visitGoal = req.body.visitgoal; // 到访问目的
    const visittime = req.body.visittime; // 到访问时间
    const education = req.body.education; // 学历
    const company = req.body.company; //公司，单位

    var sql = "UPDATE  y_user  SET username = ?,age = ?,sex = ?,visitgoal = ?,visittime = ?,education = ?,company = ? WHERE uid = ?";
    var parameters = [userName,  age, sex, visitGoal, visittime, education, company,id];
    // console.log('parameters >> ',parameters);
    querydb(sql, parameters).then(function (data) {
        console.log("修改数据成功!" + JSON.stringify(data)); //JSON.stringify()【将一个对象解析成字符串】
        res.send({
            resultCode: 1,
            resultInfo: 'ok',
        });
    })

})

// ======================================
// ============banner管理================
// ======================================
router.get('/banner', (req,res,next) => {
    const sql = 'SELECT id,url,content,number FROM y_banner ORDER BY number DESC'; 
    querydb(sql).then(data=>{
        if(data != null && data.length > 0){
            res.send({
                resultCode: 1,
                resultInfo: {
                    list: data
                },
            })
        }else{
            res.send({
                resultCode: -1,
                resultInfo: '没有数据',
            });
        }
    })
})


//=======================================
//==============日志模块=================
//=======================================
/**
 * 添加日志接口
 * url: /api/logadd
 * method: post
 * params: 1. content 日志内容   
 *         2. logtime 日志创建时间
 *         3. mid     操作员id
 */
router.post("/api/logadd", (req, res, next) => {
    let content = req.body.content;
    let logtime = req.body.logtime;
    let mid = req.body.mid;
    let category = req.body.category;

    // console.log("content: " + content + ",  logtime :" + logtime + "  ,mid :" + mid);
    var sql = "INSERT INTO  y_log (content,logtime,m_id,category)VALUES (?,?,?,?)";
    var parameters = [content, logtime, mid,category];

    querydb(sql, parameters).then(function (data) {
        console.log("添加日志数据成功!" + JSON.stringify(data)); //JSON.stringify()【将一个对象解析成字符串】
        res.send({
            resultCode: 1,
            resultInfo: 'ok',
        });
    });
})


/**
 * 日志列表
 * url: /api/log/list_page
 * method: get
 * params: 
 *     1. pageNo 当前页号 如: pageNo=1
 *     2. name: 昵称 
 *     3. startTime: 开始时间
 *     4. endTime: 结束时间
 */
router.get("/api/log/list_page", async (req, res) => {
    var totalNo = 0; // 总记录条数
    var pagesNum = 0; // 总页数
    // ===接收参数页号====
    var currentNo = req.query.pageNo; // 当前页号
    if (currentNo == null && typeof (currentNo) === 'undefined') {
        currentNo = 1;
    }
    var pageSize = req.query.pageSize; // 当前页号
    if (pageSize == null && typeof (pageSize) === 'undefined') {
        pageSize = 5;
    } else {
        pageSize = parseInt(pageSize);
    }
    // console.log('currentNo :' + currentNo, " usrename :" + req.query.username + " pageSize :"+pageSize);
    //2020-6.22 用户名,只显示当前用户日志
    const username = req.query.username;

    //查询条件
    //====昵称====
    const name = req.query.name;
    //===时间====
    const startTime = req.query.startTime;
    const endTime = req.query.endTime;

    let sqlCount = "SELECT count(*) as num FROM y_log WHERE 1=1";
    if (name) {
        sqlCount = `${sqlCount} AND m_id = (SELECT m_id FROM y_manager WHERE nick='${name.trim()}')`;
    }
    if (startTime && endTime) {
        sqlCount = `${sqlCount} AND logtime BETWEEN  '${startTime.trim()}'  AND '${endTime.trim()}'`;
    }
    //2020-6.22 用户名,只显示当前用户日志
    if (username && username != 'zhousir') {
        sqlCount = `${sqlCount} AND m_id = (SELECT m_id FROM y_manager WHERE username='${username.trim()}')`;
    }

    let data = await querydb(sqlCount);
    totalNo = data[0].num; // 总记录条数
    if (totalNo % pageSize === 0) {
        pagesNum = totalNo / pageSize;
    } else {
        pagesNum = totalNo / pageSize + 1;
    }
    // ==== 根据偏移量查询分页记录
    var start = (currentNo - 1) * pageSize; // 偏移量

    var sql = "SELECT l_id,content,logtime,y_log.m_id, username, nick,category FROM y_log,y_manager WHERE y_manager.m_id = y_log.m_id ";
    if (name) {
        sql = `${sql} AND y_manager.nick='${name.trim()}' `;
    }
    if (startTime && endTime) {
        sql = `${sql} AND logtime BETWEEN  '${startTime.trim()}'  AND '${endTime.trim()}'`;
    }
    //2020-6.22 用户名,只显示当前用户日志
    if (username && username != 'zhousir') {
        sql = `${sql} AND y_manager.username='${username.trim()}' `;
    }

    sql = `${sql} ORDER BY l_id DESC  LIMIT ?, ?`

    var param = [start, pageSize];
    let dataTwo = await querydb(sql, param);
    if (dataTwo != null && dataTwo.length > 0) {

        //=================================================
        //========= filter forEach是异步循环================
        //=================================================
        // const replayAsync = async (dataTwo) => {
        //     return dataTwo.filter(async item => {
        //         let logId = item.l_id;
        //         // console.log(`logId >>> ${logId}`);
        //         const sql = "SELECT id, message, reply_time, nick, username, headerimg FROM y_reply, y_manager WHERE y_reply.user_id = y_manager.m_id AND log_id = ?";
        //         var parameters = [logId];
        //         let dataReply = await querydb(sql, parameters);
        //         // console.log('dataReply >>> :',JSON.stringify(dataReply));
        //         if (dataReply != null && dataReply.length > 0) {
        //             item.logList = dataReply;
        //         } else {
        //             item.logList = []
        //         }
        //     })
        // }
        // let newDataList = await replayAsync(dataTwo);

        for (let index = 0; index < dataTwo.length; index++) {
            const item = dataTwo[index];
            let logId = item.l_id;
            // console.log(`logId >>> ${logId}`);
            const sql = "SELECT id, message, reply_time, nick, username, headerimg FROM y_reply, y_manager WHERE y_reply.user_id = y_manager.m_id AND log_id = ?";
            var parameters = [logId];
            let dataReply = await querydb(sql, parameters);
            if (dataReply != null && dataReply.length > 0) {
                item.logList = dataReply;
            } else {
                item.logList = []
            }

        }

        res.send({
            resultCode: 1,
            resultInfo: {
                total: totalNo,
                currentNo: parseInt(currentNo),
                pageSize: parseInt(pageSize),
                totalNum: parseInt(pagesNum),
                list: dataTwo
            },
        })
    } else {
        res.send({
            resultCode: -1,
            resultInfo: '没有数据',
        });
    }

});

/**
 * 查询日志
 * url:/api/log/find
 * parms: id
 */
router.get("/api/log/find", function (req, res, next) {
    var id = req.query.id; //接收表单参数
    if (!id) {
        res.send({
            resultCode: -1,
            resultInfo: '参数出错',
        });
        return;
    }

    var sql = "SELECT l_id,content,logtime,category FROM y_log WHERE l_id = ?";
    var parameters = [id];

    querydb(sql, parameters).then(function (data) {
        res.send({
            resultCode: 1,
            resultInfo: data[0],
        });
    }).catch(next);

});

/**
 * 修改日志
 * 
 */
router.post("/api/log/update", function (req, res) {
    var id = req.body.id;
    var content = req.body.content; //接收表单用户名参数

    var sql = "UPDATE  y_log  SET content = ? WHERE l_id = ?";
    var parameters = [content, id];
    querydb(sql, parameters).then(function (data) {

        res.send({
            resultCode: 1,
            resultInfo: 'ok',
        });
    });

});


/**
 * 删除日志
 */
router.get('/api/log/delete', (req, res, next) => {
    const id = req.query.id;
    const sql = "DELETE FROM y_log WHERE l_id = ?";
    const params = [id];
    querydb(sql, params).then(data => {
        res.send({
            resultCode: 1,
            resultInfo: 'ok'
        })
    })
})



/**
 * 根据日志Id查看 回复列表
 */
router.get("/api/reply/list", (req, res) => {
    let logId = req.query.logId;
    console.log(`logId >>> ${logId}`);
    const sql = "SELECT id, message, reply_time, nick, username, headerimg FROM y_reply, y_manager WHERE y_reply.user_id = y_manager.m_id AND log_id = ?";
    var parameters = [logId];
    querydb(sql, parameters).then(function (data) {
        console.log(JSON.stringify(data));
        if (data != null && data.length > 0) {
            res.send({
                resultCode: 1,
                resultInfo: data,
            })
        } else {
            res.send({
                resultCode: -1,
                resultInfo: '没有数据',
            });
        }
    })
})

/**
 * 添加回复
 */
router.post("/api/reply/add", (req, res, next) => {
    let message = req.body.message;
    let userId = req.body.mid;
    let logId = req.body.log_id;
    let replyTime = new Date();
    console.log("message: " + message + ",  userId :" + userId + "  ,logId :" + logId);

    var sql = "INSERT INTO  y_reply (message,reply_time,user_id,log_id)VALUES (?,?,?,?)";
    var parameters = [message, replyTime, userId, logId];

    querydb(sql, parameters).then(function (data) {
        console.log("添加回复数据成功!" + JSON.stringify(data)); //JSON.stringify()【将一个对象解析成字符串】
        res.send({
            resultCode: 1,
            resultInfo: 'ok',
        });
    });
})

/**
 * 修改日志
 * 
 */
router.post("/api/reply/update", function (req, res) {
    var id = req.body.id;
    var message = req.body.message; //接收表单用户名参数

    var sql = "UPDATE  y_reply  SET message = ? WHERE id = ?";
    var parameters = [message, id];
    querydb(sql, parameters).then(function (data) {
        res.send({
            resultCode: 1,
            resultInfo: 'ok',
        });
    });

});

/**
 * 删除日志
 */
router.get('/api/reply/delete', (req, res, next) => {
    const id = req.query.id;
    const sql = "DELETE FROM y_reply WHERE id = ?";
    const params = [id];
    querydb(sql, params).then(data => {
        res.send({
            resultCode: 1,
            resultInfo: 'ok'
        })
    })
})

module.exports = router;